import React, {
  Component,
  Fragment
} from 'react';
import TodoItem from './TodoItem'

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: "",
      list: []
    };
    this.handleButtonClick = this.handleButtonClick.bind(this)

  }

  render() {
    return (
      <Fragment>
        <div>
          {/* 用label获取input框的焦点 */}
          <label htmlFor="Sinput">输入框</label>
          <input
            id="Sinput"
            value={this.state.inputValue}
            onChange={this.handleInputChange.bind(this)}
          />
          <button onClick={this.handleButtonClick}>提交</button>
        </div>
        <ul>
          {
            this.getTodoItem()
          }
        </ul>
      </Fragment>
    );
  }

  handleInputChange(e) {
    this.setState({ inputValue: e.target.value });
    // console.log(e)
    // const value = e.target.value
    // this.setState(() => ({
    //   inputValue: value
    // })
    // )
  }

  handleButtonClick() {
    // this.setState({
    //   list: [...this.state.list, this.state.inputValue]
    // });
    this.setState((prevState) => ({
      list: [...this.state.list, this.state.inputValue]
    }));

  }
  handleItemDelete(index) {
    // const list = [...this.state.list];
    
    this.setState((prevState) => {
      const list =  [...prevState.list]
      list.splice(index, 1)
      return { list: list}
    })
  }
  getTodoItem() {
    return (
      this.state.list.map((item, index) => {
        return (
          <div key={index}>
            <TodoItem
              content={item}
              index={index}
              deleteItem={this.handleItemDelete.bind(this)} />
            {/*
                <li key={item} 
                  // dangerouslySetInnerHTML={{__html: item}}
                  onClick={this.handleItemDelete.bind(this,index)}>
                  {item}
                </li>
              */}
          </div>

        );
      })
    )
  }
}

export default TodoList;
